# -*- coding: utf-8 -*-

import foodom as dom

def match(select, tree):
    masks = {'*':lambda x: isinstance(x, dom.Element),
             '#':lambda x: x.attr('id'),
             '.':lambda x: x.attr('class'),
             '[':lambda x: x.attr(curdata),
             'e':lambda x: x.name == curdata}
    matched = list(tree.filter(masks['*'], True, True))
    curdata= ''
    step = 0
    mask = 'e'
    maxindex = len(select) - 1
    for index, char in enumerate(select):
        if step == 0:
            if char == '*':
                continue
            elif char == '#':
                matched = list(filter(masks[mask],
                                      matched)) if curdata else matched
                mask = '#'
                curdata = ''
            elif char == '.':
                matched = list(filter(masks[mask],
                                      matched)) if curdata else matched
                mask = '.'
                curdata = ''
            elif char == '[':
                matched = list(filter(masks[mask],
                                      matched)) if curdata else matched
                mask = '['
                curdata = ''
                step = 1
            elif index == maxindex:
                curdata += char
                matched = list(filter(masks[mask], matched))
            elif char == ' ':
                matched = list(filter(masks[mask], matched))
                curdata = ''
                new = []
                mask = masks['*']
                for element in matched:
                    new += list(element.filter(mask, True, True))
                matched = new
                mask = 'e'
            else:
                curdata += char
        elif step == 1:
            if char == ']':
                matched = list(filter(masks[mask], matched))
                mask = 'e'
                curdata = ''
                step = 0
            else:
                curdata += char
    return matched

selectors = ['body',
             'html body',
             'title',
             'link[rel]',
             'link[rel][type]',
             'p',
             '.last',
             'body h1',
             'html body p',
             'html title',
             '#para2',
             'html #para2',
             'p.last',
             'p#para2']

print(dom.tree)
print()
print(' === Test Series ===')
for selector in selectors:
    matched = match2(selector, dom.tree)
    print()
    print('Selector : {}.'.format(selector))
    print('Is there a match? {}.'.format({True:'Yes',
                                          False:'No'}[bool(matched)]))
    matched = [i.name for i in matched]
    print('Matched element are : {}.'.format(matched))
